from logging.config import fileConfig
import os
from dotenv import load_dotenv  # 引入dotenv加载环境变量
from sqlalchemy import engine_from_config, pool
from alembic import context
from sqlalchemy.ext.asyncio import create_async_engine, AsyncConnection


# 加载.env文件（从项目根目录加载）
env_path = os.path.join(os.path.dirname(__file__), "../../.env")
load_dotenv(env_path)

# 导入当前服务的模型Base
from friend_service.database import Base  # 从friend_service的database模块导入Base
target_metadata = Base.metadata  # 指定迁移的元数据（模型定义）

# 从环境变量获取数据库配置，注入到alembic配置
config = context.config
section = config.config_ini_section

# 将环境变量中的数据库配置映射到alembic.ini的占位符
config.set_section_option(section, "MYSQL_USER", os.getenv("MYSQL_USER"))
config.set_section_option(section, "MYSQL_PASSWORD", os.getenv("MYSQL_PASSWORD"))
config.set_section_option(section, "MYSQL_HOST", os.getenv("MYSQL_HOST"))
config.set_section_option(section, "MYSQL_PORT", os.getenv("MYSQL_PORT", "3306"))
config.set_section_option(section, "MYSQL_DB_FRIEND", os.getenv("MYSQL_DB_FRIEND"))

# 日志配置（默认即可）
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# def run_migrations_offline() -> None:
#     """离线模式迁移（生成SQL脚本）"""
#     url = config.get_main_option("sqlalchemy.url")
#     context.configure(
#         url=url,
#         target_metadata=target_metadata,
#         literal_binds=True,
#         dialect_opts={"paramstyle": "named"},
#     )

#     with context.begin_transaction():
#         context.run_migrations()

# 2. 移除同步的 run_migrations_offline，或保留但修改（异步迁移主要用 online 模式）
def run_migrations_offline() -> None:
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
        # 新增：指定异步方言（适配 asyncmy）
        dialect_name="mysql+asyncmy"
    )
    with context.begin_transaction():
        context.run_migrations()


# def run_migrations_online() -> None:
#     """在线模式迁移（直接执行SQL）"""
#     connectable = engine_from_config(
#         config.get_section(config.config_ini_section, {}),
#         prefix="sqlalchemy.",
#         poolclass=pool.NullPool,
#     )

#     with connectable.connect() as connection:
#         context.configure(
#             connection=connection, target_metadata=target_metadata
#         )

#         with context.begin_transaction():
#             context.run_migrations()

# 3. 重写 run_migrations_online 为异步函数
async def run_migrations_online_async() -> None:
    # 3.1 用 create_async_engine 创建异步引擎（替换同步的 engine_from_config）
    connectable = create_async_engine(
        config.get_main_option("sqlalchemy.url"),
        poolclass=pool.NullPool,  # 异步模式不需要连接池（或按需配置）
    )

    # 3.2 用 async with 获取异步连接
    async with connectable.connect() as connection:
        # 3.3 将异步连接绑定到 Alembic 上下文
        await connection.run_sync(
            lambda sync_conn: context.configure(
                connection=sync_conn,
                target_metadata=target_metadata
            )
        )

        # 3.4 异步事务中执行迁移
        async with context.begin_transaction():
            await context.run_migrations()

# 4. 调用异步迁移函数（需用 asyncio.run 启动事件循环）
def run_migrations_online() -> None:
    import asyncio
    asyncio.run(run_migrations_online_async())

if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()
